<?php
require_once('scripts.conf.php');

class SendBookingRemind
{
	private $db_bo = null;
	function __construct() {
                
	}
	
	/**
	 * Initialization
	 */
	function initialize() {
		/////////////////////////////////////////////////////
		// x. Create a connection to the main database
		if (!$this->db_bo = @mysql_connect(DATABASE_MAIN_SERVER, DATABASE_MAIN_LOGIN, DATABASE_MAIN_PASSWORD, true,128)) {
			/////////////////////////////////////////////////////////////
			// Logging
			writeLog(ERROR_DETAIL_CONNECTION,LOG_ERR);

			return false;
		} 
		if (!@mysql_select_db(DATABASE_MAIN_NAME, $this->db_bo)) {
			/////////////////////////////////////////////////////////////
			// Logging
            writeLog(ERROR_DETAIL_CONNECTION,LOG_ERR);

			return false;
		}
		mysql_query("SET NAMES 'utf8'", $this->db_bo);


		/////////////////////////////////////////////////////////////
		// x. Load parameters
		if (!$this->loadParameters()) {
			/////////////////////////////////////////////////////////////
			// Logging
			writeLog('Cannot load parameters',LOG_ERR);
			
			return false;
		}

		return true;
	}
	
	/**
	 * Load parameters
	 */
	function loadParameters() {
		$query = 'SELECT NOM, VALUE'.
				' FROM PARAMETER';
   				  
		if (!$result = mysql_query($query, $this->db_bo)) {
			///////////////////////////////////////////////////////////// 
			// Logging
		writeLog(mysql_error($this->db_bo).':'.$query, LOG_ERR);
			
			return false;
		}

		while ($row = mysql_fetch_assoc($result)) {
			if (!defined($row['NOM'])) {
				define($row['NOM'], $row['VALUE']);
			}				
		}
		
		return true;
	}
	
	


	/**
	 * Main process
	 */
	function execute()
	{
		/////////////////////////////////////////////////////////////
		// x. Initialize database connections
		if (!$this->initialize()) {
			return false;
		}
		
		$sql = "SELECT B.ID FROM BOOKING B
				INNER JOIN BOOKING_DETAIL BD ON BD.ID_BOOKING = B.ID
				WHERE DATE(BD.BOOKING_DATE) = DATE(DATE_ADD(NOW(),INTERVAL 2 DAY)) 
					AND DATE(DATE_ADD(B.DATE_CREATION,INTERVAL 4 DAY)) <=  DATE(BD.BOOKING_DATE)
					AND B.IS_REMINDED = 0
				GROUP BY B.ID";
		$rs = mysql_query($sql,$this->db_bo);
		$bookingList = array();
		$bookingIDs = array();
		while($row = mysql_fetch_array($rs)){
			$bookingList[] = array("ID_BOOKING"=>$row['ID'],"STATUS"=>$row['STATUS'],"REASON"=>$row['REASON']);
			$bookingIDs[$row['ID_BOOKING']] = $row['ID'];
		}
		if(count($bookingIDs)==0){
			return true;
		}
		$bookingData = $this->getbookingDetail($bookingIDs);
		foreach($bookingList as $booking){
			if(!isset($bookingData[$booking['ID_BOOKING']])){
				continue;
			}
			$data = $bookingData[$booking['ID_BOOKING']];
			$smarty = new Smarty();
			$smarty->left_delimiter =  '<{';
			$smarty->right_delimiter =  '}>';
			$smarty->template_dir = TEMPLATE_DIR;
			$smarty->compile_dir  = TEMPLATE_C_DIR;
			$smarty->config_dir  = TEMPLATE_DIR;
			$smarty->assign("bookingData",$data);
			$template = "email/booking_remind.html";
			$subject = "NAILS-TIME.COM : Your appointment with Springbank Nails Time Spa";
			$html = $smarty->fetch($template);
			/*
			echo "C:\\wamp\www\\nailstime\\bo\\application\\files\\".$booking['ID_BOOKING'].".html" . "/n";
			file_put_contents("C:\\wamp\www\\nailstime\\bo\\application\\files\\".$booking['ID_BOOKING'].".html", $html);
			 * 
			 */
			
			$mail = new html_mime_mail("X-Mailer: Html Mime Mail Class");
			$mail->add_html($html, "");
			$mail->set_charset("utf-8", TRUE);
			$mail->build_message();
			//-- Function send to mail
			//send($to_name, $to_addr, $from_name, $from_addr, $subject = '', $headers = '')
			
			//$mail->send($data['USER_INFO']['FIRST_NAME'],$data['USER_INFO']['EMAIL'],"Nails-time",NO_REPLY_SENDER_EMAIL,$subject,"");
			//die();
			$this->updateReminded($booking['ID_BOOKING']);
		}
		
	}
	function getbookingDetail($bookingIDs){
		$query = "SELECT B.ID, BD.ID_TECHNICIAN, T.TITLE TECHNICIAN_NAME, BD.BOOKING_DATE, 
					BDS.ID_SERVICE_BOOKING, SB.TITLE SERVICE_TITLE, SB.TIME,SB.PRICE, 
					IF(B.ID_MEMBER > 0, M.FIRST_NAME,B.FIRST_NAME) U_FIRST_NAME,
					IF(B.ID_MEMBER > 0, M.LAST_NAME,B.LAST_NAME) U_LAST_NAME,
					IF(B.ID_MEMBER > 0, M.PHONE,B.PHONE) U_PHONE,
					IF(B.ID_MEMBER > 0, M.EMAIL,B.EMAIL) U_EMAIL,
                    B.STATUS,
					B.ID_MEMBER
				FROM BOOKING B
				INNER JOIN BOOKING_DETAIL BD ON BD.ID_BOOKING = B.ID
				INNER JOIN BOOKING_DETAIL_SERVICE BDS ON BDS.ID_BOOKING_DETAIL = BD.ID
				INNER JOIN SERVICE_BOOKING SB ON SB.ID = BDS.ID_SERVICE_BOOKING
				LEFT JOIN TECHNICIAN T ON T.ID = BD.ID_TECHNICIAN
				LEFT JOIN MEMBER M ON M.ID = B.ID_MEMBER 
                WHERE B.ID IN (".  implode(",", $bookingIDs).") ".
				"ORDER BY B.ID,BD.ID, SB.TITLE ";
		$rs = mysql_query($query,$this->db_bo);
		$arrData = array();
		while($booking = mysql_fetch_object($rs)){
			if(!isset($arrData[$booking->ID])){
				$u = array(
						"FIRST_NAME"=>$booking->U_FIRST_NAME,
						"LAST_NAME"=>$booking->U_LAST_NAME,
						"PHONE"=>$booking->U_PHONE,
						"EMAIL"=>$booking->U_EMAIL,
						"ID_MEMBER"=>$booking->ID_MEMBER,
					);
				$arrData[$booking->ID] = array("USER_INFO"=>$u,"STATUS"=>$booking->STATUS,"TDATA"=>array());
			}
			if(!isset($arrData[$booking->ID]["TDATA"][$booking->ID_TECHNICIAN])){
				$arrData[$booking->ID]["TDATA"][$booking->ID_TECHNICIAN] = array("TITLE" => $booking->TECHNICIAN_NAME,
																	"BOOKING_DATE"=>$booking->BOOKING_DATE,
																		"SDATA" => array());
			}
			$arrData[$booking->ID]["TDATA"][$booking->ID_TECHNICIAN]["SDATA"][] = array("SID" => $booking->ID_SERVICE_BOOKING,
																				"TITLE"=>$booking->SERVICE_TITLE."(".$booking->TIME."mins  - $".$booking->PRICE.")");
		}
		return $arrData;
	}
	function updateReminded($id){
		$sql = "UPDATE BOOKING SET IS_REMINDED = 1  WHERE ID = ".$id;
		mysql_query($sql,$this->db_bo);
	}
}

///////////////////////////////////////////

///////////////////////////////////////////
// Main execution
set_time_limit(0);
ini_set("memory_limit","256M");
$lock_file = APPLICATION_DIR.'/application/files/sendBookingValidation.lock';

 $generator = new SendBookingRemind();
$generator->execute();
